package com.example.apidemo2;

import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.apidemo2.R;
import com.pos.api.Mcr;


public class McrActivity extends Activity implements OnClickListener {  
    /** Called when the activity is first created. */  
	private Mcr mcr;
	private Button btnBrush;
	private Button btnVersion;
	private Button btnSet;
	private Button btnBrush2;
	
	private TextView textRecord;
	private TextView textCount;
	private TextView textSuccess;
	private static int totalCount = 0;
	private static int successCount = 0;
    //check card timer
    private Timer mCheckCardTimer;
    private TimerTask mCheckCardTask;
    private static int CHECK_CONNECT_STATUS_TIMEOUT = 10000;//10s
	private boolean timeout = false;
	
	private static final int RECORD_PROMPT_MSG = 0x02;
	private static final int TCOUNT_PROMPT_MSG = 0x03;
	private static final int SCOUNT_PROMPT_MSG = 0x04;

	private EditText mEdTimes;
	private int mReadTimes = 1;
	
	private Handler promptHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RECORD_PROMPT_MSG:
                	showTextRecordMsg(msg);
                    break;
                case TCOUNT_PROMPT_MSG:
                	showTextCountMsg(msg);
                	break;
                case SCOUNT_PROMPT_MSG:
                	showTextSuccessMsg(msg);
                	break;
                default:
                	break;
            }

        }
    };
    
	private void showTextRecordMsg( Message msg)
	{
		Bundle b = msg.getData();
        String strInfo = b.getString("MSG");
        if(strInfo.equals("")) textRecord.setText("");
        else textRecord.append(strInfo);
	       
	}
	
	private void showTextCountMsg( Message msg)
	{
		Bundle b = msg.getData();
        String strInfo = b.getString("TCOUNT");
        if(strInfo.equals("")) textCount.setText("");
        else textCount.setText(strInfo);
	       
	}
	
	private void showTextSuccessMsg( Message msg)
	{
		Bundle b = msg.getData();
        String strInfo = b.getString("SCOUNT");
        if(strInfo.equals("")) textSuccess.setText("");
        else textSuccess.setText(strInfo);
	       
	}

	
    public void SendPromptMsg(String strInfo){
        Message msg = new Message();
        msg.what = RECORD_PROMPT_MSG;
        Bundle b = new Bundle();
        b.putString("MSG", strInfo);
        msg.setData(b);
        promptHandler.sendMessage(msg);
    }
		
    public void SendTCountMsg(String strInfo){
        Message msg = new Message();
        msg.what = TCOUNT_PROMPT_MSG;
        Bundle b = new Bundle();
        b.putString("TCOUNT", strInfo);
        msg.setData(b);
        promptHandler.sendMessage(msg);
    }
    
    public void SendSCountMsg(String strInfo){
        Message msg = new Message();
        msg.what = SCOUNT_PROMPT_MSG;
        Bundle b = new Bundle();
        b.putString("SCOUNT", strInfo);
        msg.setData(b);
        promptHandler.sendMessage(msg);
    }
	
  @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_mcr); 		
                  
		mcr = new Mcr(this, new Mcr.McrConnectStatusListener(){
			@Override
			public void onConnectResult(boolean bRet) {	
			}
		});
		
		btnBrush = (Button) findViewById(R.id.btnBrushAll);
		btnBrush.setOnClickListener(this);
		btnBrush2 = (Button) findViewById(R.id.btnBrush2);
		btnBrush2.setOnClickListener(this);
		
		btnVersion = (Button) findViewById(R.id.btnVersion);
		btnVersion.setOnClickListener(this);
		btnSet = (Button) findViewById(R.id.btnSet);
		btnSet.setOnClickListener(this);
	
		textRecord=(TextView)this.findViewById(R.id.textRecord);
		textCount=(TextView)this.findViewById(R.id.textCount);
		textSuccess=(TextView)this.findViewById(R.id.TextSuccess);

		mEdTimes = (EditText) findViewById(R.id.editMcr);
	}  

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch(v.getId())
		{
		case R.id.btnSet:
		{
			int iRet = 0;
//			byte [] mode = new byte [2];
//			mode[0] = 0x00;
			int mode[] = new int[1];
			mode[0] = 32;
			iRet = mcr.DLL_McrReadSet(mode,new String[8], new String[8]);
//			mode[0] = 0x07;
//			mode[1] = 0x44;
			mode[0] = 1860;
			String start[] = new String[8];
			String end[] = new String[8];
			start[4] = "AAAA";
			end[4] = "ZZZZ";
			iRet = mcr.DLL_McrReadSet(mode, start, end);
//			iRet = mcr.DLL_McrReadSet(mode, "AAAA".getBytes(), "ZZZZ".getBytes());
			if(iRet!=0) {SendPromptMsg("MCR mode set failed, return value is:"+Integer.toString(iRet)+"\r\n"); return;}
			else SendPromptMsg("MCR mode set success!\r\n");
		}
			break;
		case R.id.btnBrushAll:
//			new Thread() {
//				public void run() {
//					int iRet = 0;
//					byte [] track1Len = new byte [1];
//					byte [] track2Len = new byte [1];
//					byte [] track3Len = new byte [1];
//					byte [] trackLen = new byte [2];
//					byte [] track1 = new byte [256];
//					byte [] track2 = new byte [256];
//					byte [] track3 = new byte [256];
//					byte [] track = new byte [1000];
//
//					
//					SendPromptMsg("");
//					iRet = mcr.DLL_McrOpen();
//					if(iRet!=0) {SendPromptMsg("MCR open failed, return value is:"+Integer.toString(iRet)+"\r\n"); return;}
//					else SendPromptMsg("MCR open success!\r\n");
//					
//					iRet = mcr.DLL_McrReset();
//					if(iRet!=0) {SendPromptMsg("MCR reset failed, return value is:"+Integer.toString(iRet)+"\r\n"); mcr.DLL_McrClose(); return;}
//					else SendPromptMsg("MCR reset success!\r\n");			
//					
//					SendPromptMsg("Please swipe card...\r\n");
//					mCheckCardTimer = new Timer();
//					mCheckCardTask = new TimerTask() {
//			            @Override
//			            public void run() {
//			            	timeout = true;
//			            }
//			        };
//			        mCheckCardTimer.schedule(mCheckCardTask, CHECK_CONNECT_STATUS_TIMEOUT);	
//			        while(!timeout)
//					{
//						iRet = mcr.DLL_McrCheck();
//						if(iRet == 0) 
//						{
//							mCheckCardTimer.cancel();
//							break;
//						}
//					}
//			        if(timeout) {timeout = false;mcr.DLL_McrClose(); SendPromptMsg("Swipe card timeout\r\n");return;}
//					totalCount++;
//					SendTCountMsg("swipe count:"+Integer.toString(totalCount));
//					SendPromptMsg("Detect card swiped\r\n");
//					//iRet = mcr.DLL_McrRead(track1Len,track1,track2Len,track2,track3Len,track3);	
//					iRet = mcr.DLL_McrReadAllData(trackLen, track);
//					if(iRet > 0)
//					{
//						successCount++;
//						SendSCountMsg("success count:"+Integer.toString(successCount));		
//						
//						String string = "";
//						if(iRet <= 7){
//							/*if((iRet & 0x01) == 0x01)
//								string = "track1:" + new String(track1).trim();
//							if((iRet & 0x02) == 0x02)
//								string = string + "\r\ntrack2:" + new String(track2).trim();
//							if((iRet & 0x04) == 0x04)
//								string = string + "\r\ntrack3:" + new String(track3).trim();*/
//							string = "track:" + new String(track).trim();
//						}else{
//							string = "McrRead data error\r\n";
//						}					
//						SendPromptMsg(string);
//						mcr.DLL_McrClose();
//                        SendPromptMsg("\r\nMCR close,Test Success\r\n");
//					}
//					else
//					{
//						SendSCountMsg("success count:"+Integer.toString(successCount));				
//						SendPromptMsg("Read card failed!!!\r\n"); 
//						mcr.DLL_McrClose();
//
//					}	
//				}
//			}.start();
			//textCount.setText("swipe count:"+Integer.toString(totalCount));
			//textSuccess.setText("success count:"+Integer.toString(successCount));				
			break;
			
		case R.id.btnBrush2:
			if(TextUtils.isEmpty(mEdTimes.getText())){
				mReadTimes = 1;
			}else {
				mReadTimes = Integer.parseInt(mEdTimes.getText().toString());
				if (mReadTimes <= 0)
					mReadTimes = 1;
			}
			Toast.makeText(McrActivity.this,"读" + mReadTimes + "次",Toast.LENGTH_SHORT).show();
			readMsr();
			break;
		case R.id.btnVersion:
//			byte [] version = new byte [100];
//			
//			SendPromptMsg("");			
//			iRet = mcr.DLL_McrReadVersion(version);
//			if(iRet !=0) SendPromptMsg("Read MCR version failed!!!\r\n"); 
//			else SendPromptMsg("MCR version is: " + new String(version).trim());
			break;
		}
	}

	public void readMsr(){
		new Thread(){
			public void run()
			{
				int iRet = 0;
				byte [] track1Len = new byte [1];
				byte [] track2Len = new byte [1];
				byte [] track3Len = new byte [1];
				byte [] trackLen = new byte [2];
				byte [] track1 = new byte [256];
				byte [] track2 = new byte [256];
				byte [] track3 = new byte [256];
				byte [] track = new byte [1000];

				for(int i =0; i< mReadTimes; i++){
					SendPromptMsg("");
					iRet = mcr.DLL_McrOpen();
					if(iRet!=0) {SendPromptMsg("MCR open failed, return value is:"+Integer.toString(iRet)+"\r\n"); return;}
					else SendPromptMsg("MCR open success!\r\n");

					iRet = mcr.DLL_McrReset();
					if(iRet!=0) {SendPromptMsg("MCR reset failed, return value is:"+Integer.toString(iRet)+"\r\n"); mcr.DLL_McrClose(); return;}
					else SendPromptMsg("MCR reset success!\r\n");

					SendPromptMsg("Please swipe card...\r\n");
					mCheckCardTimer = new Timer();
					mCheckCardTask = new TimerTask() {
						@Override
						public void run() {
							timeout = true;
						}
					};
					mCheckCardTimer.schedule(mCheckCardTask, CHECK_CONNECT_STATUS_TIMEOUT);
					while(!timeout)
					//while(true)
					{
						iRet = mcr.DLL_McrCheck();
						Log.i("unifou", iRet + "DLL_McrCheck");
						if(iRet == 0)
						{
							mCheckCardTimer.cancel();
							break;
						}
					}

					if(timeout) {timeout = false;mcr.DLL_McrClose(); SendPromptMsg("Swipe card timeout\r\n");return;}
					totalCount++;
					SendTCountMsg("swipe count:"+Integer.toString(totalCount));
					SendPromptMsg("Detect card swiped\r\n");
					//iRet = mcr.DLL_McrRead(track1Len,track1,track2Len,track2,track3Len,track3);

					iRet = mcr.DLL_McrRead(track1Len, track1, track2Len, track2, track3Len, track3);
					if(iRet > 0)
					{
						successCount++;
						SendSCountMsg("success count:"+Integer.toString(successCount));

						String string = "";
						if(iRet <= 7){
							if((iRet & 0x01) == 0x01)
								string = "track1:" + new String(track1).trim();
							if((iRet & 0x02) == 0x02)
								string = string + "\r\ntrack2:" + new String(track2).trim();
							if((iRet & 0x04) == 0x04)
								string = string + "\r\ntrack3:" + new String(track3).trim();
//							string = "track:" + new String(track).trim();
						}else{
							string = "McrRead data error\r\n";
						}
						SendPromptMsg(string);
						mcr.DLL_McrClose();
						SendPromptMsg("\r\nMCR close,Test Success\r\n");
					}
					else
					{
						SendSCountMsg("success count:"+Integer.toString(successCount));
						SendPromptMsg("Read card failed!!!\r\n"+iRet);
						mcr.DLL_McrClose();
					}
					SystemClock.sleep(1000);
				}

			};
		}.start();
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(null!= mcr) mcr.DLL_McrRelease();
		super.onDestroy();
	}  
}

